<?php

class lang_instance
{
	public function __construct($langPath)
	{
		$this->SetLangPath($langPath);
		$this->Load('default');
	}
	
	private $_langData = array();
	
	public function Translate($text, $params, $isDebug = null)
	{
		$upperText = strtoupper($text);
		if (isset($this->_langData[$upperText]))
		{
			$text = $this->_langData[$upperText];	
		}
		else if ($isDebug)
		{
			$text = '••' .$text. '••';
		}
	
		if (is_array($params) && sizeof($params))
		{
			array_unshift($params, $text);
			$text = call_user_func_array('sprintf', $params);
		}
		
		return $text;
	}
	
	private $_packsLoaded = array();
	
	public function Load($packName = 'default')
	{
		if (isset($this->_packsLoaded[$packName])) return;
		$this->_packsLoaded[$packName] = true;
		
		$langFile = $this->GetLangPath().$packName. '.php';
		if (!is_file($langFile)) return;
		
		$packData = array_change_key_case(include($langFile), CASE_UPPER);
		
		$this->_langData = (array)$packData + $this->_langData;
	}

	private $_path = false;
	
	private function SetLangPath($path)
	{
		if (!is_dir($path)) throw new Exception('Invalid lang path');
		$this->_path = rtrim($path, '/\\'). '/';
	}

	private function GetLangPath()
	{
		return $this->_path;
	}	
}